package com.ctshk.rpc.visa.service.impl;

import cn.hutool.core.collection.CollectionUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ctshk.common.dto.Result;
import com.ctshk.common.enums.MessageDataType;
import com.ctshk.common.enums.MessageType;
import com.ctshk.common.enums.SystemError;
import com.ctshk.common.enums.VisaSource;
import com.ctshk.common.exception.BusinessException;
import com.ctshk.common.model.TokenUser;
import com.ctshk.common.utils.EntityUtil;
import com.ctshk.rpc.system.dto.MainDataCurrencyQueryDTO;
import com.ctshk.rpc.system.dto.MainDataRowFieldDataDTO;
import com.ctshk.rpc.system.dto.UserDTO;
import com.ctshk.rpc.system.req.MainDataCurrencyUpdateStatusReq;
import com.ctshk.rpc.system.req.MainDataRowFieldDataReq;
import com.ctshk.rpc.system.req.SysMessageReq;
import com.ctshk.rpc.system.service.IMainDataCurrencyService;
import com.ctshk.rpc.system.service.IMainDataTableService;
import com.ctshk.rpc.system.service.ISysUserService;
import com.ctshk.rpc.system.service.ISystemMessageService;
import com.ctshk.rpc.visa.dto.visa.VisaCertificatesDTO;
import com.ctshk.rpc.visa.dto.visa.VisaOrderTouristDTO;
import com.ctshk.rpc.visa.entity.*;
import com.ctshk.rpc.visa.mapper.*;
import com.ctshk.rpc.visa.req.visa.*;
import com.ctshk.rpc.visa.service.IVisaOrderTouristService;
import io.seata.spring.annotation.GlobalTransactional;
import net.sf.json.JSONArray;
import org.apache.commons.lang3.StringUtils;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * <p>
 * 签证旅客信息 服务实现类
 * </p>
 *
 * @author 谢诗宏
 * @since 2021-01-28
 */
@DubboService
public class VisaOrderTouristServiceImpl extends ServiceImpl<VisaOrderTouristMapper, VisaOrderTourist> implements IVisaOrderTouristService {

    @Autowired
    private VisaOrderTouristMapper visaOrderTouristMapper;
    @Autowired
    private VisaOrderMapper visaOrderMapper;
    @Autowired
    private VisaProductMapper visaProductMapper;
    @Autowired
    private VisaMapper visaMapper;

    @Autowired
    private VisaTypeMapper visaTypeMapper;

    @Autowired
    private VisaManageMapper visaManageMapper;

    @DubboReference
    private ISysUserService iSysUserService;

    /**
     * 系统消息服务
     */
    @DubboReference
    private ISystemMessageService systemMessageService;

    @DubboReference
    private IMainDataTableService mainDataTableService;

    @Override
    public Result<List<VisaOrderTouristDTO>> list(VisaOrderTouristReq visaOrderTouristReq) {
        QueryWrapper<VisaOrderTourist> wrapper = new QueryWrapper<>();
        wrapper.eq("is_deleted", 0);
        wrapper.eq("order_id", visaOrderTouristReq.getOrderId());
        List<VisaOrderTourist> visaOrderTouristList = visaOrderTouristMapper.selectList(wrapper);
        List<VisaOrderTouristDTO> visaOrderTouristDTOS = new ArrayList<>();

        // 旅客信息判断
        if (CollectionUtil.isEmpty(visaOrderTouristList)) {
            throw new BusinessException(SystemError.VISA_ORDER_25007);
        }

        List<VisaCertificatesDTO> visaCertificatesDTOList = new ArrayList<>();
        // 旅客遍历
        for (VisaOrderTourist visaOrderTourist : visaOrderTouristList) {
            VisaOrderTouristDTO visaOrderTouristDTO = EntityUtil.copy(visaOrderTourist, VisaOrderTouristDTO.class);

            // 证件信息
            VisaCertificatesDTO visaCertificatesDTO = new VisaCertificatesDTO();
            String certificatesJson = visaOrderTourist.getCertificatesJson();
            List<VisaCertificatesDTO> certificatesDTOS = new ArrayList<>();
            if (StringUtils.isNotBlank(certificatesJson)) {
                certificatesDTOS = JSON.parseObject(certificatesJson, new TypeReference<ArrayList<VisaCertificatesDTO>>() {
                });
                List<VisaCertificatesDTO> list = new ArrayList<>();
//            if (visaOrderTourist.getCertificatesTypeId() != null) {
//                visaCertificatesDTO.setCertificatesTypeId(visaOrderTourist.getCertificatesTypeId());
//            }
//            visaCertificatesDTO.setCertificatesNumber(visaOrderTourist.getCertificatesNumber());

                // 查询证件类型
                MainDataRowFieldDataReq req = new MainDataRowFieldDataReq();
                req.setFid(1348477526361763842L);
                req.setTid(1348475429155237889L);
                List<MainDataRowFieldDataDTO> rowFieldDataDTOS = mainDataTableService.queryDataFieldLikeName(req);
                for (VisaCertificatesDTO certificatesDTO : certificatesDTOS) {
                    for (MainDataRowFieldDataDTO dataDTO : rowFieldDataDTOS) {
                        Pattern pattern = Pattern.compile("[0-9]{1,}");
                        Matcher matcher = pattern.matcher((CharSequence) visaOrderTourist.getCertificatesType());
                        boolean result = matcher.matches();
                        if (result == true) {

                            if (dataDTO.getId().longValue() == Long.parseLong(visaOrderTourist.getCertificatesType())) {
                                certificatesDTO.setCertificatesTypeId(dataDTO.getId());
                                certificatesDTO.setCertificatesType(dataDTO.getFieldValue());
                            }
                        }
                    }
                    list.add(certificatesDTO);
                }

                certificatesDTOS.clear();
                for (VisaCertificatesDTO dto : list) {
                    certificatesDTOS.add(dto);
                }
            }
//            visaCertificatesDTO.setVaildDate(visaOrderTourist.getVaildDate());
            visaCertificatesDTOList.addAll(certificatesDTOS);
            if (visaOrderTourist.getOrderId() != null) {
                VisaOrder visaOrder = visaOrderMapper.selectById(visaOrderTourist.getOrderId());
                if (visaOrder == null) {
                    throw new BusinessException(SystemError.VISA_ORDER_25005);
                }

                VisaProduct visaProduct = visaProductMapper.selectById(visaOrder.getProductId());
                if (visaProduct == null) {
                    throw new BusinessException(SystemError.VISA_ORDER_25012);
                }

                QueryWrapper<VisaType> visa_id = new QueryWrapper<VisaType>().eq("visa_id", visaProduct.getVisaId()).eq("id", visaOrder.getTypeId());
                VisaType visaType = visaTypeMapper.selectOne(visa_id);
                if (visaType == null) {
                    throw new BusinessException(SystemError.VISA_ORDER_25013);
                }

                // 加幅类型判断
                if (visaProduct.getAdjustType() == 1) {
                    // 币种判断
                    if (visaType.getCurrencyId() == null) {
                        throw new BusinessException(SystemError.VISA_ORDER_25011);
                    }
                    MainDataCurrencyUpdateStatusReq mainDataCurrencyUpdateStatusReq = new MainDataCurrencyUpdateStatusReq();
                    mainDataCurrencyUpdateStatusReq.setId(visaType.getCurrencyId());
                    Result<MainDataCurrencyQueryDTO> query = iMainDataCurrencyService.query(mainDataCurrencyUpdateStatusReq);
                    visaOrderTouristDTO.setSinglePrice(visaType.getCostAmount().multiply(query.getData().getPlannedExchangeRate()));
                } else if (visaProduct.getAdjustType() == 2) {
                    visaOrderTouristDTO.setSinglePrice(visaType.getCostAmount().multiply(new BigDecimal(visaProduct.getPercent())).divide(new BigDecimal("100")));
                }
            }
            visaOrderTouristDTO.setVisaCertificatesDTOList(visaCertificatesDTOList);
            visaOrderTouristDTOS.add(visaOrderTouristDTO);
        }
        return Result.success(visaOrderTouristDTOS);
    }

    @DubboReference
    private IMainDataCurrencyService iMainDataCurrencyService;

    @Override
    public Result<List<VisaOrderTouristDTO>> handleList(VisaInfoReq visaInfoReq) {
        QueryWrapper<Visa> visaQueryWrapper = new QueryWrapper<>();
        visaQueryWrapper.eq("id", visaInfoReq.getId());
        Visa visa = visaMapper.selectOne(visaQueryWrapper);
        List<VisaOrderTouristDTO> visaOrderTouristDTOS = new ArrayList<>();
        if (visa != null) {
            QueryWrapper<VisaProduct> visaProductQueryWrapper = new QueryWrapper<>();
            visaProductQueryWrapper.eq("visa_id", visa.getId());
            VisaProduct visaProduct = visaProductMapper.selectOne(visaProductQueryWrapper);
            if (visaProduct != null) {
                QueryWrapper<VisaOrder> visaOrderQueryWrapper = new QueryWrapper<>();
                visaOrderQueryWrapper.eq("product_id", visaProduct.getId());

                // 销售单号
                visaOrderQueryWrapper.like(StringUtils.isNotBlank(visaInfoReq.getOrderNumber()), "order_number", visaInfoReq.getOrderNumber());
                List<VisaOrder> visaOrderList = visaOrderMapper.selectList(visaOrderQueryWrapper);
                if (visaOrderList != null && visaOrderList.size() >= 1) {
//                    VisaOrder visaOrder = visaOrderList.get(0);
                    for (VisaOrder order : visaOrderList) {
                        QueryWrapper<VisaOrderTourist> visaOrderTouristQueryWrapper = new QueryWrapper<>();
                        visaOrderTouristQueryWrapper.eq("order_id", order.getId());
                        visaOrderTouristQueryWrapper.eq("is_deleted", 0);

                        //旅客姓名
                        visaOrderTouristQueryWrapper.like(StringUtils.isNotBlank(visaInfoReq.getName()), "surname", visaInfoReq.getName());
                        visaOrderTouristQueryWrapper.or(StringUtils.isNotBlank(visaInfoReq.getName()));
                        visaOrderTouristQueryWrapper.like(StringUtils.isNotBlank(visaInfoReq.getName()), "name", visaInfoReq.getName());

                        visaOrderTouristQueryWrapper.groupBy("certificates_number");
                        List<VisaOrderTourist> visaOrderTouristList = visaOrderTouristMapper.selectList(visaOrderTouristQueryWrapper);
                        if (visaOrderTouristList != null) {
                            for (VisaOrderTourist visaOrderTourist : visaOrderTouristList) {
                                VisaOrderTouristDTO visaOrderTouristDTO = EntityUtil.copy(visaOrderTourist, VisaOrderTouristDTO.class);
//                            visaOrderTouristDTO = EntityUtil.copy(visaOrderTourist, VisaOrderTouristDTO.class);
                                visaOrderTouristDTO.setId(visaOrderTourist.getId());
                                visaOrderTouristDTO.setCountryName(visa.getCountryName());
                                visaOrderTouristDTO.setRemark(order.getRemark());
                                visaOrderTouristDTO.setContactName(order.getContactName());
                                visaOrderTouristDTO.setContactEmail(order.getContactEmail());
                                visaOrderTouristDTO.setPhone(order.getContactMobileAreaCode() + "-" + order.getContactMobile());

                                //上线去掉
                                UserDTO userDTO = null;
                                try {
                                    userDTO = iSysUserService.loadUserByParam(order.getCreateId(), 1);
                                    visaOrderTouristDTO.setCreateByName(userDTO.getCnSurname() + userDTO.getCnName() + "/" + userDTO.getDept() + "+" + userDTO.getMobile());
                                } catch (Exception e) {
                                    Result.failed(SystemError.SYS_500);
                                }
                                // 签证状态
                                QueryWrapper<VisaManage> wrapper = new QueryWrapper<>();
                                // 收齐状态
                                wrapper.eq(visaInfoReq.getCollectionStatus() != null, "collection_status", visaInfoReq.getCollectionStatus());
                                wrapper.eq("tourist_id", visaOrderTourist.getId());
                                // 出签状态
                                wrapper.eq(visaInfoReq.getVisa_status() != null, "visa_status", visaInfoReq.getVisa_status());
                                VisaManage visaManage = visaManageMapper.selectOne(wrapper);
                                if (visaManage != null) {
                                    visaOrderTouristDTO.setVisa_status(visaManage.getVisaStatus());
                                    visaOrderTouristDTO.setCollectionStatus(visaManage.getCollectionStatus());
                                    visaOrderTouristDTO.setAirWaybillNumber(visaManage.getAirWaybillNumber());
                                    visaOrderTouristDTO.setSubmitTime(visaManage.getSubmitTime());
                                }
                                List<VisaCertificatesDTO> visaCertificatesDTOList = new ArrayList<>();
                                String certificatesNumber = visaOrderTourist.getCertificatesNumber();
                                QueryWrapper<VisaOrderTourist> visaOrderTouristQueryWrapper1 = new QueryWrapper<>();
                                visaOrderTouristQueryWrapper1.eq("certificates_number", certificatesNumber);
                                List<VisaOrderTourist> visaOrderTouristList1 = visaOrderTouristMapper.selectList(visaOrderTouristQueryWrapper1);
                                if (visaOrderTouristList1 != null) {
                                    for (VisaOrderTourist visaOrderTourist1 : visaOrderTouristList1) {
                                        VisaCertificatesDTO visaCertificatesDTO = new VisaCertificatesDTO();
                                        visaCertificatesDTO.setCertificatesType(visaOrderTourist1.getCertificatesType());
                                        visaCertificatesDTO.setCertificatesNumber(visaOrderTourist1.getCertificatesNumber());
                                        visaCertificatesDTO.setVaildDate(visaOrderTourist1.getVaildDate());
                                        visaCertificatesDTOList.add(visaCertificatesDTO);
                                    }
                                    visaOrderTouristDTO.setVisaCertificatesDTOList(visaCertificatesDTOList);
                                }
                                visaOrderTouristDTOS.add(visaOrderTouristDTO);
                            }
                        }
                    }
                }
            }
        }
        return Result.success(visaOrderTouristDTOS);
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Result modify(VisaOrderTouristModifyReq visaOrderTouristModifyReq, TokenUser tokenUser) {
        VisaOrderTourist visaOrderTourist = visaOrderTouristMapper.selectById(visaOrderTouristModifyReq.getId());
        if (visaOrderTourist != null) {
            List<VisaCertificatesDTO> certificatesDTOList = visaOrderTouristModifyReq.getVisaCertificatesDTOList();
//            for (VisaCertificatesDTO visaCertificatesDTO : certificatesDTOList) {
//                visaOrderTourist.setCertificatesNumber(visaCertificatesDTO.getCertificatesNumber());
//                visaOrderTourist.setVaildDate(visaCertificatesDTO.getVaildDate());
//                visaOrderTourist.setCertificatesTypeId(visaCertificatesDTO.getCertificatesTypeId());
//                visaOrderTourist.setCertificatesType(visaCertificatesDTO.getCertificatesType());
//            }
            JSONArray jsonArray = JSONArray.fromObject(certificatesDTOList);
            visaOrderTourist.setCertificatesJson(jsonArray.toString());
            visaOrderTourist.setGender(Integer.parseInt(visaOrderTouristModifyReq.getTouristType()));
            visaOrderTourist.setSurname(visaOrderTouristModifyReq.getSurname());
            visaOrderTourist.setName(visaOrderTouristModifyReq.getName());
            visaOrderTourist.setTouristType(visaOrderTouristModifyReq.getTouristType());
            visaOrderTourist.setBirthday(visaOrderTouristModifyReq.getBirthday());
            visaOrderTourist.setGmtModified(LocalDateTime.now());
            visaOrderTourist.setModifiedId(tokenUser.getId());
            visaOrderTouristMapper.updateById(visaOrderTourist);
        }
        return Result.success(visaOrderTourist.getId());
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Result register(VisaManageRegisterReq visaManageRegisterReq, TokenUser currentUser) {
        QueryWrapper<VisaManage> wrapper = new QueryWrapper<>();
        wrapper.eq("tourist_id", visaManageRegisterReq.getTouristId());
        VisaManage visaManage = visaManageMapper.selectOne(wrapper);
        if (null != visaManage) {
            visaManage.setVisaStatus(1);
            visaManage.setSubmitTime(visaManageRegisterReq.getSubmitTime());
            visaManage.setCollectionStatus(1);
            visaManage.setCollectionRemark(visaManageRegisterReq.getCollectionRemark());
            visaManage.setModifiedId(currentUser.getId());
            int result = visaManageMapper.updateById(visaManage);
            if (result >= 1) {
                VisaOrderTourist orderTourist = visaOrderTouristMapper.selectById(visaManageRegisterReq.getTouristId());
                if (orderTourist != null) {
                    QueryWrapper<VisaOrder> wrapper1 = new QueryWrapper<>();
                    wrapper1.eq("order_number", orderTourist.getOrderId());
                    VisaOrder visaOrder = visaOrderMapper.selectOne(wrapper1);
                    if (visaOrder != null) {
                        SysMessageReq sysDepartmentReq = new SysMessageReq();

                        // 销售单号
                        sysDepartmentReq.setBusinessOrderNo(visaOrder.getOrderNumber());
                        // 业务id
                        sysDepartmentReq.setBusinessId(visaOrder.getId());
                        // 销售人
                        sysDepartmentReq.setReceivingUserId(visaOrder.getCreateId());
                        sysDepartmentReq.setType(MessageType.INFORM.getCode());
                        sysDepartmentReq.setBusinessType(MessageDataType.DATA_TYPE_37.getCode());
                        sysDepartmentReq.setTitle("签证资料变更通知");
                        sysDepartmentReq.setSource(VisaSource.getVisaSourceName(1));
                        return systemMessageService.add(sysDepartmentReq, currentUser.getId());
                    }
                }
            }
        }
        return Result.failed(SystemError.SYS_419);
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Result sendSign(VisaManageSignSendReq visaManageSignSendReq, TokenUser currentUser) {
        QueryWrapper<VisaManage> wrapper = new QueryWrapper<>();
        wrapper.eq("tourist_id", visaManageSignSendReq.getTouristId());
        VisaManage visaManage = visaManageMapper.selectOne(wrapper);
        if (null != visaManage) {
            visaManage.setSendTime(visaManageSignSendReq.getSendTime());
            visaManageMapper.updateById(visaManage);
        }
        return Result.success();
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Result signSuccess(VisaManageSignSuccessReq visaManageSignSuccessReq, TokenUser currentUser) {
        QueryWrapper<VisaManage> wrapper = new QueryWrapper<>();
        wrapper.eq("tourist_id", visaManageSignSuccessReq.getTouristId());
        VisaManage visaManage = visaManageMapper.selectOne(wrapper);
        if (null != visaManage) {
            visaManage.setAirWaybillNumber(visaManageSignSuccessReq.getAirWaybillNumber());
            visaManage.setExpressDeliveryTime(visaManageSignSuccessReq.getExpressDeliveryTime());
            visaManage.setReceiptFile(visaManageSignSuccessReq.getReceiptFile());
            visaManage.setVisaFile(visaManageSignSuccessReq.getVisaFile());
            visaManage.setCreateId(currentUser.getId());
            visaManageMapper.updateById(visaManage);
        }
        return Result.success();
    }

    @Override
    @GlobalTransactional(rollbackFor = Exception.class)
    public Result signFailure(VisaManageSignFailureReq visaManageSignFailureReq, TokenUser currentUser) {
        QueryWrapper<VisaManage> wrapper = new QueryWrapper<>();
        wrapper.eq("tourist_id", visaManageSignFailureReq.getTouristId());
        VisaManage visaManage = visaManageMapper.selectOne(wrapper);
        if (null != visaManage) {
            visaManage.setAirWaybillNumber(visaManageSignFailureReq.getAirWaybillNumber());
            visaManage.setExpressDeliveryTime(visaManageSignFailureReq.getExpressDeliveryTime());
            visaManage.setReceiptFile(visaManageSignFailureReq.getReceiptFile());
            visaManageMapper.updateById(visaManage);
        }
        return Result.success();
    }

}
